package com.campus.gateway.util;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * 生成JSON Web令牌的工具类
 */
public class JwtHelper {

    //token过期时间
    private static long tokenExpiration = 60 * 60 * 1000;
    //加密秘钥
    private static String tokenSignKey = "viper3";

    //根据用户id和用户名称生成token字符串
    public static String createToken(Integer userId) {
        String token = Jwts.builder()
                .setSubject("AUTH-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    //从token字符串获取userid
    public static int getUserId(String token) {
        try {
            if (StringUtils.isEmpty(token)) return 0;

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            int userId = (int) claims.get("userId");
            return userId;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    //从token字符串获取username
    public static String getUsername(String token) {
        try {
            if (StringUtils.isEmpty(token)) return "";

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("username");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static boolean validateToken(String token) {
        try {
            // 验证token的合法性和完整性
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);

            // 验证token的有效期
            Date expirationDate = claimsJws.getBody().getExpiration();
            if (expirationDate.before(new Date())) {
                // token已过期
                System.out.println("token已过期~");
                return false;
            }

            System.out.println("有效token~");
            return true;
        } catch (Exception e) {
            // 解析或验证token出错
            e.printStackTrace();
            return false;
        }
    }

    public static void main(String[] args) {
        String token = "eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAA_6tWKi5NUrJScgwN8dANDXYNUtJRSq0oULIyNDc2MjUytjQ211EqLU4t8kwBitUCAGMy-LYvAAAA.KXw1KJiDIlKb62EaXz5I7hX-s_M1KTiiTmJWxW8MuXI462TEywtMn0fTBQScI1VBmTNVzWiVDIberQDRq6hG_A";
        System.out.println(token);

        Integer userId = JwtHelper.getUserId(token);
        System.out.println(userId);

    }
}
